package com.sky.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduAddressUtil {
    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    private static String mapUrl = "https://api.map.baidu.com/geocoding/v3/";

    private static String ak = "ZtIZuPjH8cCp2xnnCz3LZ3felG5KjXVK";

    /**
     * 根据地址获取经纬度
     */
    public static Map<String, Double> GetLatLngByBaidu(String address) throws IOException {
        Map<String, Double> map = new HashMap<String, Double>();
        String url = mapUrl + "?address=" + address + "&output=json&ak=" +
                ak + "&ret_coordtype=gcj02ll";
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }

        ObjectMapper mapper = new ObjectMapper();
        JsonNode obj = mapper.readValue(json.toString(), JsonNode.class);

        if (obj.get("status").toString().equals("0")) {
            JsonNode location = obj.get("result").get("location");
            double lng = location.get("lng").asDouble();
            double lat = location.get("lat").asDouble();
            map.put("lng", lng);
            map.put("lat", lat);
        } else {
            return null;
        }
        return map;
    }

    /**
     * 计算两个经纬度之间的距离
     */
    public static double GetDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(
                Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000);
        return s;
    }
}
